#include <QList>
#include <QByteArray>
#include <QFileDialog>
#include <QSplitter>
#include <QGridLayout>

#include "Logger.h"
#include "bibleebookwidget.h"
#include "bibleebookitem.h"
#include "biblereaderdownloader.h"

BibleEbookWidget::BibleEbookWidget(BibleReaderCore *brCore, QWidget *parent)
    :QWidget(parent)
{
    bibleReaderCore = brCore;

    ebookPath = bibleReaderCore->getConfigurator()->getBePathBase();

    createWidgets();
}

BibleEbookWidget::~BibleEbookWidget()
{
}

void BibleEbookWidget::readBook(QString identify)
{

}


void BibleEbookWidget::downloadBook(QString bookName, QString identify, QString bookUrl)
{
    LOG_INFO() << "downloading " << bookName << " from:" << bookUrl;
    QString saveBookPath = ebookPath.append("/").append(identify);

    QDir ebookDir(saveBookPath);
    if (!ebookDir.exists()) {
        ebookDir.mkpath(saveBookPath);
    }

    saveBookFilePath = saveBookPath.append("/").append(bookName).append(".epub");

    if (!bookUrl.isEmpty()) {
        BibleReaderDownloader *downloader = new BibleReaderDownloader(bookUrl, this);
        connect(downloader, &BibleReaderDownloader::finished, this, &BibleEbookWidget::saveBook);
        downloader->start();
    }

}

void BibleEbookWidget::saveBook()
{
    LOG_INFO() << "saving " << saveBookFilePath;
    auto *dl =  qobject_cast<BibleReaderDownloader*>(sender());

    if (dl->getErrorCode() == QNetworkReply::NoError) {
        QFile f(saveBookFilePath);
        f.open(QIODevice::WriteOnly);

        f.write(dl->getData());
        f.flush();

        f.close();
    } else {
        LOG_ERROR() << "NetWork error: " << dl->getErrorCode();
    }
}

void BibleEbookWidget::saveReadHistory(QString identify, int pageNum)
{

}

void BibleEbookWidget::saveBookmark(QString identify, int pageNum)
{

}

void BibleEbookWidget::createWidgets()
{
    searchBookField = new QLineEdit(this);
    goSearchBtn = new QPushButton(tr("Search"), this);


    bookCategories = new QTreeWidget(this);
    bookCategories->setHeaderLabel(tr("Book Category"));

    bookListArea = new QScrollArea(this);

    // book list widget
    bookList = new QWidget(this);
    bookList->setObjectName("bookList");
    QGridLayout *listLayout = new QGridLayout;
    for (int i = 0; i < 5 ; i++) {
        for (int j = 0; j < 5; j++) {
           listLayout->addWidget(new BibleEBookItem(bookList), i, j);
        }
    }
    bookList->setLayout(listLayout);

    bookListArea->setWidget(bookList);

    QHBoxLayout *hLayout = new QHBoxLayout;
    hLayout->addWidget(searchBookField, 8);
    hLayout->addWidget(goSearchBtn, 2);

    QSplitter *splitter = new QSplitter(this);
    splitter->addWidget(bookCategories);
    splitter->addWidget(bookListArea);

    QVBoxLayout *vLayout = new QVBoxLayout;
    vLayout->addLayout(hLayout, 2);
    vLayout->addWidget(splitter, 8);

    this->setLayout(vLayout);
}


